package com.jjb.www.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.layout.ShapeRecyclerView;
import com.hjq.shape.layout.ShapeRelativeLayout;
import com.hjq.shape.view.ShapeImageView;
import com.hjq.shape.view.ShapeTextView;
import com.jjb.www.R;
import com.jjb.www.app.AppFragment;
import com.jjb.www.bean.BannerBean;
import com.jjb.www.http.api.AgencyListApi;
import com.jjb.www.http.api.CertDetitleApi;
import com.jjb.www.http.api.CertListApi;
import com.jjb.www.http.api.CheckCostApi;
import com.jjb.www.http.api.CompleteApplyApi;
import com.jjb.www.http.api.GetPlanStudentInfoApi;
import com.jjb.www.http.api.StaydoApi;
import com.jjb.www.http.api.TipsApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.http.model.HttpList;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.activity.CopyActivity;
import com.jjb.www.ui.activity.LearningRecordsActivity;
import com.jjb.www.ui.activity.PreEmploymentActivity;
import com.jjb.www.ui.activity.SequentialPracticeActivity;
import com.jjb.www.ui.activity.SequentialPracticeV2Activity;
import com.jjb.www.ui.activity.VerificationRecordActivity;
import com.jjb.www.ui.activity.VipActivity;
import com.jjb.www.ui.adapter.BannerListAdapter;
import com.jjb.www.ui.adapter.IndicatorAdapter;
import com.jjb.www.ui.dialog.GraduationDialog;
import com.jjb.www.ui.dialog.MessageDialog;
import com.jjb.www.ui.dialog.MessageJJBDialog;
import com.jjb.www.ui.dialog.NoUserVipDialog;
import com.jjb.www.ui.dialog.RuleDialog;
import com.jjb.www.widget.CircularProgressView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnPageChangeListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * author : Android CRG
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18Indicator
 * desc   : 学习
 */
public final class StudyListFragment extends AppFragment<CopyActivity> {
    private BannerListAdapter bannerListAdapter;
    private Banner mBanner;
    private ShapeRecyclerView mRvIndicator;
    private IndicatorAdapter indicatorAdapter;
    private ShapeTextView mTvBannerSort;
    private ShapeTextView mTvTotalScore;
    private ShapeTextView mTvAlreadyTotalScore;
    private ShapeTextView mTvStudyState1;
    private ShapeTextView mTvStudyStateText1;
    private ShapeTextView mTvNotScore1;
    private CircularProgressView mProgress1;
    private ShapeTextView mTvAlreadyScore1;
    private ShapeTextView mTvButton1;
    private ShapeTextView mTvStudyState2;
    private ShapeTextView mTvStudyStateText2;
    private ShapeTextView mTvNotScore2;
    private CircularProgressView mProgress2;
    private ShapeTextView mTvAlreadyScore2;
    private ShapeTextView mTvButton2;
    private ShapeTextView mTvStudyState3;
    private ShapeTextView mTvStudyStateText3;
    private ShapeTextView mTvNotScore3;
    private CircularProgressView mProgress3;
    private ShapeTextView mTvAlreadyScore3;
    private ShapeTextView mTvButton3;
    private ShapeImageView mImgStudyState1;
    private ShapeImageView mImgStudyState2;
    private ShapeImageView mImgStudyState3;
    private ShapeRelativeLayout mRlView;
    private ShapeTextView mTvSchoolName;
    private ShapeImageView mImgPhone;
    private ShapeTextView mTvGraduation;



    private ShapeTextView mTvSchoolAddress;
    private ShapeLinearLayout mLlLearningRecords;
    private ShapeTextView mTvRule;
    private Integer certId;
    private TipsApi.Bean tipBean;
    private List<String> idk = new ArrayList<>();
    private static final String INTENT_KEY_IN_CERT_TYPE = "certType";
    private static final String INTENT_KEY_IN_TYPE = "type";
    private String student_id = "0";
    //结业弹窗数据
    private String DialogGraduation = "";
    //sdk需要的参数
    private CertDetitleApi.Bean.SdkInfoDTO sdkInfoDTO;
    public static StudyListFragment newInstance(Integer type,String certType) {
        StudyListFragment fragment = new StudyListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(INTENT_KEY_IN_CERT_TYPE, certType);
        bundle.putInt(INTENT_KEY_IN_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_study_list;
    }

    @Override
    protected void initView() {
        mRvIndicator = findViewById(R.id.rv_indicator);
        mBanner = findViewById(R.id.banner);
        mTvRule = findViewById(R.id.tv_rule);
        mTvBannerSort = findViewById(R.id.tv_banner_sort);
        mRlView = findViewById(R.id.rl_view);
        mLlLearningRecords = findViewById(R.id.ll_learning_records);
        mTvSchoolName = findViewById(R.id.tv_school_name);
        mImgPhone = findViewById(R.id.img_phone);
        mTvGraduation = findViewById(R.id.tv_graduation);
        mTvSchoolAddress = findViewById(R.id.tv_school_address);
        mImgStudyState1 = findViewById(R.id.img_study_state1);
        mImgStudyState2 = findViewById(R.id.img_study_state2);
        mImgStudyState3 = findViewById(R.id.img_study_state3);
        mTvTotalScore = findViewById(R.id.tv_total_score);
        mTvAlreadyTotalScore = findViewById(R.id.tv_already_total_score);
        mTvStudyState1 = findViewById(R.id.tv_study_state1);
        mTvStudyStateText1 = findViewById(R.id.tv_study_state_text1);
        mTvNotScore1 = findViewById(R.id.tv_not_score1);
        mProgress1 = findViewById(R.id.progress1);
        mTvAlreadyScore1 = findViewById(R.id.tv_already_score1);
        mTvButton1 = findViewById(R.id.tv_button1);
        mTvStudyState2 = findViewById(R.id.tv_study_state2);
        mTvStudyStateText2 = findViewById(R.id.tv_study_state_text2);
        mTvNotScore2 = findViewById(R.id.tv_not_score2);
        mProgress2 = findViewById(R.id.progress2);
        mTvAlreadyScore2 = findViewById(R.id.tv_already_score2);
        mTvButton2 = findViewById(R.id.tv_button2);
        mTvStudyState3 = findViewById(R.id.tv_study_state3);
        mTvStudyStateText3 = findViewById(R.id.tv_study_state_text3);
        mTvNotScore3 = findViewById(R.id.tv_not_score3);
        mProgress3 = findViewById(R.id.progress3);
        mTvAlreadyScore3 = findViewById(R.id.tv_already_score3);
        mTvButton3 = findViewById(R.id.tv_button3);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvIndicator.setLayoutManager(layoutManager);

        indicatorAdapter = new IndicatorAdapter(getContext());
        indicatorAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                indicatorAdapter.setItemSel(position + 1);
                mBanner.setCurrentItem(position + 1);
                mTvBannerSort.setText("(" + (position + 1) + "/" + idk.size() + ")");
            }
        });
        mRvIndicator.setAdapter(indicatorAdapter);
        setOnClickListener(mTvRule,mLlLearningRecords,mTvButton1,mTvButton2,mTvButton3,mTvGraduation);
    }

    @Override
    protected void initData() {
        getCertList();

        mBanner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                CertListApi.Bean bean = bannerListAdapter.getData(position);
                certId = bean.getId();
                getCertDetitls(bean.getId() + "", bean.getCard_book_id() + "");
                mRvIndicator.smoothScrollToPosition(position);
                indicatorAdapter.setItemSel(position);
                mTvBannerSort.setText("(" + (position + 1) + "/" + idk.size() + ")");
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void getTips() {
        EasyHttp.get(this)
                .api(new TipsApi()
                .setId(certId+"")
                .setType(getInt(INTENT_KEY_IN_TYPE)+""))
                .request(new HttpCallback<HttpData<TipsApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TipsApi.Bean> data) {
                        tipBean = data.getData();
                        new RuleDialog.Builder(getContext())
                                .setTitle(tipBean.getTable_title())
                                .settable_th(tipBean.getTable_th())
                                .settable_td1(tipBean.getTable_tr().get(0).getTable_td())
                                .settable_td2(tipBean.getTable_tr().get(1).getTable_td())
                                .settable_td3(tipBean.getTable_tr().get(2).getTable_td())
                                .setListener(new RuleDialog.OnListener() {
                                    @Override
                                    public void onCompleted(BaseDialog dialog) {
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                }).show();
                    }
                });
    }

    @Override
    public void onClick(View view) {
        if (view==mTvRule){
            getTips();
        }else if (view==mLlLearningRecords){
            Intent intent = new Intent();
            intent.putExtra("id_card",sdkInfoDTO.getId_card()+"");
            intent.putExtra("planCode",sdkInfoDTO.getPlanCode()+"");
            intent.putExtra("student_id",student_id+"");
            intent.putExtra("trainPostCode",sdkInfoDTO.getTrainPostCode()+"");
            intent.setClass(getContext(),VerificationRecordActivity.class);
            startActivity(intent);
        }else if (view==mTvButton1){

        }
        else if (view==mTvButton2){
            startActivity(PreEmploymentActivity.class);
        }else if (view==mTvGraduation){

        }

        else if (view==mTvButton3){
            Intent intent = new Intent();
            intent.putExtra("certId",certId);
            intent.setClass(getContext(), LearningRecordsActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 获取培训详情考生机构信息
     * @param type 岗位type
     *      //(于代办一样)2八大员继续教育 3岗前培训 4实名认证 5完善信息 6考评员培训
     *     // 7检测人员专项测评 8检测人员专项领取合格证 9安管继教培训 10安管继教测评 11农村工匠培训
     *     // 12监理人员专项培训 13 监理人员专项测评 14监理人员专项领取结业证 15特种作业人员继教 16安管人员继教
     */
    private void GetPlanStudentInfo(Integer type,String student_id){
        EasyHttp.get(this)
                .api(new GetPlanStudentInfoApi()
                .setType(type+"")
                .setStudent_id(student_id))
                .request(new HttpCallback<HttpData<GetPlanStudentInfoApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<GetPlanStudentInfoApi.Bean> data) {
                        if (data.getData()!=null){
                            mRlView.setVisibility(View.VISIBLE);
                            mTvSchoolName.setText(data.getData().getMech_name());
                            mTvSchoolAddress.setText(data.getData().getSchool_address());
                        }else {
                            mRlView.setVisibility(View.GONE);
                        }
                    }

                });
    }
    /**
     * 获取证书详情 规则
     */
    private void getCertDetitls(String id, String card_book_id) {
        EasyHttp.get(this)
                .api(new CertDetitleApi()
                        .setClient_type("1")
                        .setCard_book_id(card_book_id)
                        .setId(id)
                )
                .request(new HttpCallback<HttpData<CertDetitleApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<CertDetitleApi.Bean> data) {
                        CertDetitleApi.Bean bean = data.getData();
                        DialogGraduation = bean.getHeader_title();
                        if (bean.getComplete_status()==1){
                            //结业弹窗
                            dialogGraduation();
//                            mTvGraduation.setVisibility(View.VISIBLE);
                        }else if (bean.getComplete_status()==2){
//                            mTvGraduation.setVisibility(View.GONE);
                            //测评弹窗
                            dialogEvaluation();
                        }

                        sdkInfoDTO = bean.getSdk_info();
                        mTvTotalScore.setText(bean.getTotal_score() + "");
                        mTvAlreadyTotalScore.setText(bean.getAlready_total_score() + "");

                        CertDetitleApi.Bean.ModeListDTO list1 = bean.getMode_list().get(0);
                        mTvStudyStateText1.setText(list1.getScore_type_desc() + "");
                        String time = "需要获得<font color='#F0332A' size='50px'>" + list1.getScore() + "</font>学时";
                        mTvNotScore1.setText(Html.fromHtml(time));
//                        int number = (list1.getAlready_score() / list1.getScore()) * 100;
                        BigDecimal score1 = new BigDecimal(list1.getAlready_score());
                        BigDecimal score2 = new BigDecimal(list1.getScore());
                        BigDecimal percentage = score1.divide(score2, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                        mProgress1.setProgress(percentage.intValue(),1000);
                        mTvAlreadyScore1.setText(list1.getAlready_score() + "");
                        mTvButton1.setText(list1.getButton());
//                        for (CertDetitleApi.Bean.ModeListDTO listDTO:bean.getMode_list()) {
//                            if (!listDTO.getAlready_score().equals(listDTO.getScore())){
//                                isDialogGraduation = false;
//                            }
//                        }
//                        if (isDialogGraduation){
//                            //全部学完弹窗
//
////
//                        }


                        if (list1.getAlready_score() == 0) {
                            //未学习
                            mTvStudyState1.setText("未学习");
                            mImgStudyState1.setImageResource(R.mipmap.icon_study_wxm);
                            mTvStudyState1.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_ED4B4D))
                                    .intoTextColor();
                        } else if (list1.getAlready_score().equals(list1.getScore())) {
                            //已修满
                            mTvStudyState1.setText("已修满");
                            mImgStudyState1.setImageResource(R.mipmap.icon_study_yxm);
                            mTvStudyState1.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_18B566))
                                    .intoTextColor();
                        } else {
                            //学习中
                            mTvStudyState1.setText("学习中");
                            mImgStudyState1.setImageResource(R.mipmap.icon_study_xxz);
                            mTvStudyState1.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_3675FE))
                                    .intoTextColor();
                        }

                        CertDetitleApi.Bean.ModeListDTO list2 = bean.getMode_list().get(1);
                        student_id = list2.getStudent_id();
                        GetPlanStudentInfo(getInt(INTENT_KEY_IN_TYPE),list2.getStudent_id());
                        mTvStudyStateText2.setText(list2.getScore_type_desc() + "");
                        String time2 = "需要获得<font color='#F0332A' size='50px'>" + list2.getScore() + "</font>学时";
                        mTvNotScore2.setText(Html.fromHtml(time2));
                        BigDecimal bigDecimal2 = new BigDecimal(list2.getAlready_score());
                        BigDecimal bigDecimaltotal = new BigDecimal(list2.getScore());
                        BigDecimal percentage2 = bigDecimal2.divide(bigDecimaltotal, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                        mProgress2.setProgress(percentage2.intValue(),1000);

                        mTvAlreadyScore2.setText(list2.getAlready_score() + "");
                        mTvButton2.setText(list2.getButton());
                        if (list2.getAlready_score() == 0) {
                            //未学习
                            mTvStudyState2.setText("未学习");
                            mImgStudyState2.setImageResource(R.mipmap.icon_study_wxm);
                            mTvStudyState2.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_ED4B4D))
                                    .intoTextColor();
                        } else if (list2.getAlready_score().equals(list2.getScore())) {
                            //已修满
                            mTvStudyState2.setText("已修满");
                            mImgStudyState2.setImageResource(R.mipmap.icon_study_yxm);
                            mTvStudyState2.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_18B566))
                                    .intoTextColor();
                        } else {
                            //学习中
                            mTvStudyState2.setText("学习中");
                            mImgStudyState2.setImageResource(R.mipmap.icon_study_xxz);
                            mTvStudyState2.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_3675FE))
                                    .intoTextColor();
                        }

                        CertDetitleApi.Bean.ModeListDTO list3 = bean.getMode_list().get(2);
                        mTvStudyStateText3.setText(list3.getScore_type_desc() + "");
                        String time3 = "需要获得<font color='#F0332A' size='50px'>" + list3.getScore() + "</font>学时";
                        mTvNotScore3.setText(Html.fromHtml(time3));

                        BigDecimal bigDecimal3 = new BigDecimal(list3.getAlready_score());
                        BigDecimal bigDecimaltotal3 = new BigDecimal(list3.getScore());
                        BigDecimal percentage3 = bigDecimal3.divide(bigDecimaltotal3, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                        mProgress3.setProgress(percentage3.intValue(),1000);

                        mTvAlreadyScore3.setText(list3.getAlready_score() + "");
                        mTvButton3.setText(list3.getButton());
                        if (list3.getAlready_score() == 0) {
                            //未学习
                            mTvStudyState3.setText("未学习");
                            mImgStudyState3.setImageResource(R.mipmap.icon_study_wxm);
                            mTvStudyState3.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_ED4B4D))
                                    .intoTextColor();
                        } else if (list3.getAlready_score().equals(list3.getScore())) {
                            //已修满
                            mTvStudyState3.setText("已修满");
                            mImgStudyState3.setImageResource(R.mipmap.icon_study_yxm);
                            mTvStudyState3.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_18B566))
                                    .intoTextColor();
                        } else {
                            //学习中
                            mTvStudyState3.setText("学习中");
                            mImgStudyState3.setImageResource(R.mipmap.icon_study_xxz);
                            mTvStudyState3.getTextColorBuilder()
                                    .setTextColor(ContextCompat.getColor(getContext(), R.color.color_3675FE))
                                    .intoTextColor();
                        }
                    }
                });
    }

    @SuppressLint("ResourceType")
    private void dialogEvaluation() {
        new MessageJJBDialog.Builder(getActivity())
                // 标题可以不用填写
//                .setTitle(R.mipmap.icon_cp_tips)
                // 内容必须要填写
                .setMessage(DialogGraduation)
                // 确定按钮文本
                .setConfirm("立即测评")
                // 设置 null 表示不显示取消按钮
                .setCancel("暂不测评")
                // 设置点击按钮后不关闭对话框
//                    .setAutoDismiss(false)
                .setListener(new MessageJJBDialog.OnListener() {

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        cePinData();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {

                    }
                })
                .show();
    }

    private void cePinData() {
        EasyHttp.get(this)
                .api(new CheckCostApi()
                        )
                .request(new HttpCallback<HttpData<CheckCostApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<CheckCostApi.Bean> data) {
                        Intent intent = new Intent();
                        intent.putExtra("fromType","ceping");
                        intent.putExtra("quick",3);
                        intent.putExtra("student_id",student_id+"");
                        intent.putExtra("certificate_id",certId+"");
                        intent.setClass(getContext(), SequentialPracticeV2Activity.class);
                        startActivity(intent);
                    }
                });
    }

    private void dialogGraduation() {
        new GraduationDialog.Builder(getActivity())
                // 标题可以不用填写
//                .setTitle("我是标题")
                // 内容必须要填写
                .setContent(DialogGraduation)
                .setTost("结业申请审核通过后，才能延期证书")
                // 确定按钮文本
                .setConfirm("申请结业")
                // 设置 null 表示不显示取消按钮
                .setCancel(null)
                // 设置点击按钮后不关闭对话框
//                    .setAutoDismiss(false)
                .setListener(new GraduationDialog.OnListener() {

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        //结业
                        completeApply();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {

                    }
                })
                .show();
    }

    private void completeApply() {
        EasyHttp.get(this)
                .api(new CompleteApplyApi()
                .setId(certId+""))
                .request(new HttpCallback<HttpData<CompleteApplyApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<CompleteApplyApi.Bean> data) {

                    }
                });
    }

    /**
     * 获取证书列表
     */
    private void getCertList() {
        EasyHttp.get(this)
                .api(new CertListApi()
                        .setType(getString(INTENT_KEY_IN_CERT_TYPE)))
                .request(new HttpCallback<HttpList<CertListApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpList<CertListApi.Bean> data) {
                        mTvBannerSort.setText("(1/" + data.getData().size() + ")");
                        bannerListAdapter = new BannerListAdapter(getContext(), data.getData());
                        mBanner.setAdapter(bannerListAdapter);
                        idk.clear();
                        for (CertListApi.Bean bean : data.getData()) {
                            idk.add("");
                        }
                        certId = data.getData().get(0).getId();
                        getCertDetitls(data.getData().get(0).getId() + "", data.getData().get(0).getCard_book_id() + "");

                        indicatorAdapter.setData(idk);
                        indicatorAdapter.setItemSel(0);
                    }
                });
    }
}